﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NCC_SOP.app_codes;
using System.Data;
using Telerik.Web.UI;
using System.Collections;

namespace NCC_SOP
{
    public partial class bodyMap : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                MultiView1.ActiveViewIndex = 0;
                Session["OptionsAdded"] = null;
                resetColumnsInSelectedHistology();
                bindDataToOptionsList();
                setUpDiagnosisYear();
                setUpBodyMapImageMapping();

            }
        }

        private void bindDataToOptionsList()
        {
            dbConnection db = new dbConnection();
            string[] options = db.getAllBodyMapOptions();
            options = removeExistingOptionsInPlaceHolder(options);
            OptionsList.DataSource = options;
            OptionsList.DataBind();
        }

        private string[] removeExistingOptionsInPlaceHolder(string[] options)
        {
            ArrayList al = new ArrayList();
            ArrayList optionsAdded = new ArrayList();
            if (Session["OptionsAdded"] != null)
            {
                optionsAdded = (ArrayList)Session["OptionsAdded"];
            }
            foreach (string s in options)
            {
                if (!optionsAdded.Contains(s))
                {
                    al.Add(s);
                }
            }
            return (string[])al.ToArray(System.Type.GetType("System.String"));
        }

        private void setUpDiagnosisYear()
        {
            int year = DateTime.Today.Year;
            int[] years = new int[10];
            for (int i = 0; i < 10; i++)
            {
                years[i] = year + i - 9;
            }
            StartYear.DataSource = years;
            StartYear.DataBind();
            EndYear.DataSource = years;
            EndYear.DataBind();
        }

        private void setUpBodyMapImageMapping()
        {
            try
            {
                dbConnection db = new dbConnection();
                int[] IDs = db.getAllHotSpotIDs();
                ImageMap im;
                foreach (int id in IDs)
                {
                    DataTable dt = db.getHotSpotDetails(id);

                    if (dt.Rows[0]["LeftOrRight"].ToString().Equals("Left"))
                    {
                        im = BodyLeftMap;
                    }
                    else
                    {
                        im = BodyRightMap;
                    }
                    RectangleHotSpot rhs1 = new RectangleHotSpot();
                    RectangleHotSpot rhs2 = new RectangleHotSpot();
                    rhs1.AlternateText = dt.Rows[0]["Label"].ToString();
                    rhs1.PostBackValue = id.ToString();
                    rhs2.AlternateText = dt.Rows[0]["Label"].ToString();
                    rhs2.PostBackValue = id.ToString();

                    try
                    {
                        rhs1.Left = Convert.ToInt32(dt.Rows[0]["ImgLeft"].ToString());
                        rhs1.Right = Convert.ToInt32(dt.Rows[0]["ImgRight"].ToString());
                        rhs1.Top = Convert.ToInt32(dt.Rows[0]["ImgTop"].ToString());
                        rhs1.Bottom = Convert.ToInt32(dt.Rows[0]["ImgBtm"].ToString());
                        im.HotSpots.Add(rhs1);

                        rhs2.Left = Convert.ToInt32(dt.Rows[0]["TextLeft"].ToString());
                        rhs2.Right = Convert.ToInt32(dt.Rows[0]["TextRight"].ToString());
                        rhs2.Top = Convert.ToInt32(dt.Rows[0]["TextTop"].ToString());
                        rhs2.Bottom = Convert.ToInt32(dt.Rows[0]["TextBtm"].ToString());
                        im.HotSpots.Add(rhs2);
                    }
                    catch (FormatException fe)
                    {
                    }
                }
            }
            catch (Exception e1)
            {
                Session["ErrorMessage"] = e1.Message;
                Response.Redirect("~/ErrorDisplayPage.aspx");
            }
        }

        protected void updateEndYear(object sender, EventArgs e)
        {
            int startYear = Convert.ToInt32(StartYear.SelectedValue);
            int endYear = Convert.ToInt32(EndYear.SelectedValue);
            int thisYear = DateTime.Today.Year;
            int[] years = new int[thisYear - startYear + 1];
            for (int i = 0; i < (thisYear - startYear + 1); i++)
            {
                years[i] = startYear + i;
            }
            EndYear.DataSource = years;
            EndYear.DataBind();
            if (endYear > startYear)
            {
                EndYear.SelectedValue = endYear.ToString();
            }
        }

        protected void checkEmptyFields(object sender, ServerValidateEventArgs e)
        {
            //check Staging Version 6
            if (StagingDiv.Style["Display"].Equals("block"))
            {
                foreach (RadTreeNode rtn1 in Staging6.Nodes)
                {
                    foreach (RadTreeNode rtn2 in rtn1.Nodes)
                    {
                        if (rtn2.Checked)
                        {
                            e.IsValid = true;
                            return;
                        }
                    }
                }

                foreach (RadTreeNode rtn1 in Staging7.Nodes)
                {
                    foreach (RadTreeNode rtn2 in rtn1.Nodes)
                    {
                        if (rtn2.Checked)
                        {
                            e.IsValid = true;
                            return;
                        }
                    }
                }
                e.IsValid = false;
                EmptyFieldValidator.ErrorMessage = "Please select at least one Staging.";
            }
        }

        protected void setUpSelectionForm(object sender, ImageMapEventArgs e)
        {
            //Display Selected Cancer
            dbConnection db = new dbConnection();
            int id = Convert.ToInt32(e.PostBackValue);
            string cancerName = db.getSelectedCancer(id);
            CancerName.Text = cancerName;

            //Display Histology
            updateRadComboBoxHistology();

            //Display Staging

            /*Display Version 6*/
            foreach (RadTreeNode rtn in Staging6.GetAllNodes())
            {
                rtn.Remove();
            }
            DataTable dt6 = db.getStaging(cancerName, "ajcc_6");
            string[] type6 = db.getStagingTypes(cancerName);
            foreach (string type in type6)
            {
                Staging6.Nodes.Add(new RadTreeNode(type));
                foreach (DataRow dr in dt6.Rows)
                {
                    RadTreeNode rtn = new RadTreeNode(dr["Staging"].ToString());
                    rtn.ToolTip = (dr["Detail"].ToString());
                    if (dr["Type"].Equals(type))
                    {
                        Staging6.Nodes.FindNodeByText(type).Nodes.Add(rtn);
                    }
                }
            }
            /*Display Version 7*/
            foreach (RadTreeNode rtn in Staging7.GetAllNodes())
            {
                rtn.Remove();
            }
            DataTable dt7 = db.getStaging(cancerName, "ajcc_7");
            string[] type7 = db.getStagingTypes(cancerName);
            foreach (string type in type7)
            {
                Staging7.Nodes.Add(new RadTreeNode(type));
                foreach (DataRow dr in dt7.Rows)
                {
                    RadTreeNode rtn = new RadTreeNode(dr["Staging"].ToString());
                    rtn.ToolTip = (dr["Detail"].ToString());
                    if (dr["Type"].Equals(type))
                    {
                        Staging7.Nodes.FindNodeByText(type).Nodes.Add(rtn);
                    }
                }
            }
        }

        protected void viewLeftBody(object sender, EventArgs e)
        {
            MultiView1.ActiveViewIndex = 0;
        }

        protected void viewRightBody(object sender, EventArgs e)
        {
            MultiView1.ActiveViewIndex = 1;
        }

        protected void updateRadComboBoxHistology()
        {
            dbConnection db = new dbConnection();
            string[] histology = db.getHistologyList(CancerName.Text);
            ArrayList newHistology = new ArrayList();
            DataTable dt = retrieveDataTableFromSelectedHistology();
            bool found = false;
            foreach (string s in histology)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    if (dr["CancerName"].Equals(CancerName.Text) && dr["Histology"].Equals(s))
                    {
                        found = true;
                    }
                }
                if (!found)
                {
                    newHistology.Add(s);
                }
                found = false;
            }
            RadComboBoxHistology.DataSource = newHistology;
            RadComboBoxHistology.DataBind();
        }

        protected void updateSelection(object sender, EventArgs e)
        {
            Page.Validate();
            if (!Page.IsValid)
            {
                return;
            }
            //Retrieve Cancer Type
            string cancerName = CancerName.Text;

            // Add Selection Into SelectedHistology
            DataTable dt = retrieveDataTableFromSelectedHistology();
            DataRow newRow = dt.NewRow();
            newRow["CancerName"] = cancerName;
            ArrayList columns = new ArrayList();
            if (Session["OptionsAdded"] != null)
            {
                columns = (ArrayList)Session["OptionsAdded"];
            }
            foreach (string column in columns)
            {
                switch (column)
                {
                    case "Histology":
                        newRow["Histology"] = RadComboBoxHistology.SelectedValue;
                        break;
                    case "Diagnosis Year":
                        newRow["Diagnosis Year"] = StartYear.Text+"-"+EndYear.Text;
                        break;
                    case "Staging":
                        newRow["Staging"] = retrieveStringForStaging(retrieveSelectedStagings());;
                        break;
                }
            }
            dt.Rows.Add(newRow);
            SelectedHistology.DataSource = dt;
            SelectedHistology.DataBind();
            updateRadComboBoxHistology();

        }

        private static string retrieveStringForStaging(ArrayList stagings)
        {
            string stringForStaging = "";
            foreach (Staging_Object so in stagings)
            {
                stringForStaging += so.version + "," + so.type + ",";
                foreach (string stage in so.staging)
                {
                    stringForStaging += stage + ",";
                }
                stringForStaging += " ";
            }
            return stringForStaging;
        }

        private DataTable retrieveDataTableFromSelectedHistology()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("CancerName");
            ArrayList columns = new ArrayList();
            if (Session["OptionsAdded"] != null)
            {
                columns = (ArrayList)Session["OptionsAdded"];
            }
            foreach (string s in columns)
            {
                dt.Columns.Add(s);
            }
            foreach (GridDataItem gdi in SelectedHistology.Items)
            {
                DataRow dr = dt.NewRow();
                dr["CancerName"] = gdi["CancerName"].Text;
                foreach (string s in columns)
                {
                    dr[s] = gdi[s].Text;
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }

        protected void SelectedHistology_DeleteCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GridEditableItem item = (GridEditableItem)e.Item;
            DataTable dt = retrieveDataTableFromSelectedHistology();
            dt.Rows.RemoveAt(item.ItemIndex);
            
            /*DataRow rowToDelete = dt.NewRow();
            foreach (DataRow dr in dt.Rows)
            {
                if (dr["CancerName"].Equals(cancerName))
                {
                    rowToDelete = dr;
                }
            }
            dt.Rows.Remove(rowToDelete);*/
            SelectedHistology.DataSource = dt;
            SelectedHistology.DataBind();
            updateRadComboBoxHistology();
        }

        protected ArrayList retrieveSelectedStagings()
        {
            ArrayList stagingObjects = new ArrayList();
            foreach (RadTreeNode rtn1 in Staging6.Nodes)
            {
                ArrayList chosen = new ArrayList();
                foreach (RadTreeNode rtn2 in rtn1.Nodes)
                {
                    if (rtn2.Checked)
                    {
                        chosen.Add(rtn2.Text);
                    }
                }
                Staging_Object so = new Staging_Object("ajcc_6", rtn1.Text, chosen);
                if (chosen.Count > 0)
                {
                    stagingObjects.Add(so);
                }
            }
            foreach (RadTreeNode rtn1 in Staging7.Nodes)
            {
                ArrayList chosen = new ArrayList();
                foreach (RadTreeNode rtn2 in rtn1.Nodes)
                {
                    if (rtn2.Checked)
                    {
                        chosen.Add(rtn2.Text);
                    }
                }
                Staging_Object so = new Staging_Object("ajcc_7", rtn1.Text, chosen);
                if (chosen.Count > 0)
                {
                    stagingObjects.Add(so);
                }
            }
            return stagingObjects;
        }

        protected ArrayList retrieveStagingObjects(string stages)
        {
            ArrayList al = new ArrayList();
            string[] strings = stages.Split(' ');
            foreach (string s in strings)
            {
                if (!String.IsNullOrEmpty(s))
                {
                    string[] details = s.Split(',');
                    ArrayList stagings = new ArrayList();
                    for (int i = 2; i < details.Length; i++)
                    {
                        stagings.Add(details[i]);
                    }
                    al.Add(new Staging_Object(details[0], details[1], stagings));
                }
            }
            return al;
        }

        protected void AddOptionButton_Click(object sender, EventArgs e)
        {
            GridBoundColumn gbc = new GridBoundColumn();
            SelectedHistology.Columns.Add(gbc);
            gbc.HeaderText = OptionsList.SelectedValue;
            gbc.DataField = OptionsList.SelectedValue;
        
            switch (OptionsList.SelectedValue)
            {
                case "Histology":
                    HistologyDiv.Style["Display"] = "block";
                    break;
                case "Diagnosis Year":
                    DiagnosisYearDiv.Style["Display"] = "block";
                    break;
                case "Staging":
                    StagingDiv.Style["Display"] = "block";
                    break;
                
                    // you can add new cases here for new options
                    // just need to have distinct div ids runat server
            }
            ArrayList optionsAdded = new ArrayList();
            if (Session["OptionsAdded"] != null)
            {
                optionsAdded = (ArrayList)Session["OptionsAdded"];
            }
            if (!String.IsNullOrWhiteSpace(OptionsList.SelectedValue))
            {
                optionsAdded.Add(OptionsList.SelectedValue);
            }
            Session["OptionsAdded"] = optionsAdded;
            bindDataToOptionsList();
        }

        protected void ResetOptionButton_Click(object sender, EventArgs e)
        {
            HistologyDiv.Style["Display"] = "none";
            DiagnosisYearDiv.Style["Display"] = "none";
            StagingDiv.Style["Display"] = "none";
            // remember to change the display of new divs to none as well

            Session["OptionsAdded"] = new ArrayList();
            resetColumnsInSelectedHistology();
            bindDataToOptionsList();
        }

        //resets the columns to only delete and cancer name
        private void resetColumnsInSelectedHistology()
        {
            SelectedHistology.Columns.Clear();
            GridButtonColumn gbc = new GridButtonColumn();
            SelectedHistology.Columns.Add(gbc);
            gbc.HeaderText = "Delete";
            gbc.CommandName = "Delete";
            gbc.UniqueName = "Delete";
            gbc.ButtonType = GridButtonColumnType.ImageButton;
            GridBoundColumn gbc1 = new GridBoundColumn();
            SelectedHistology.Columns.Add(gbc1);
            gbc1.HeaderText = "Cancer Name";
            gbc1.DataField = "CancerName";
        }

        protected void submitQuery(object sender, EventArgs e)
        {
            /*
            //Generating Histology Objects
            ArrayList histologyObjects = new ArrayList();
            DataTable dt = retrieveDataTableFromSelectedHistology();
            foreach (DataRow dr in dt.Rows)
            {
                ArrayList stagings = retrieveStagingObjects(dr["Staging"].ToString());
                histologyObjects.Add(new Histology_Object(dr["Histology"].ToString()));
            }

            int startYear = Convert.ToInt32(StartYear.SelectedValue);
            int endYear = Convert.ToInt32(EndYear.SelectedValue);

            // histologyObjects and stagingObjects are completed.

            string query = "";
            foreach (Histology_Object h_o in histologyObjects)
            {
                query += h_o.cancerType + " \n";
                query += h_o.selectedHistology + " \n";
                foreach (Staging_Object s_o in h_o.stagingObjects)
                {
                    query += s_o.version + " " + s_o.type + " ";
                    foreach (string s in s_o.staging)
                    {
                        query += s + " ";
                    }
                    query += "\n";
                }
            }
            Session["Query"] = query;
            Response.Redirect("submitQuery.aspx");
             */
        }
    }
}
